<template>
  <a-card class="general-card" title="评价管理" :bordered="false">
    <a-tabs
      @change="
        (val) => {
          apiParams.grade = val;
        }
      "
      :default-active-key="gradeStatusVar"
    >
      <a-tab-pane key="GOOD" title="好评"></a-tab-pane>
      <a-tab-pane key="MODERATE" title="中评"></a-tab-pane>
      <a-tab-pane key="WORSE" title="差评"></a-tab-pane>
    </a-tabs>
    <searchTable
      :columns="columnsSearch"
      time-type="timestamp"
      @reset="
        (val) => {
          apiParams = { ...apiParams, ...val };
        }
      "
      @search="
        (val) => {
          apiParams = { ...apiParams, ...val };
        }
      "
    ></searchTable>
    <tablePage
      ref="tablePageRef"
      :columns="columnsTable"
      :methods="sortMethods"
      :api="getMemberReview"
      :api-params="apiParams"
      :bordered="true"
      @detail="details"
    />
    <!-- 评价详情弹框 -->
    <a-modal v-model:visible="modalVisible" title="详细">
      <a-form :style="{ width: '460px' }" ref="formRef" :model="form">
        <a-form-item field="content" label="评价内容">
          <span v-if="!form.content"> 暂无评价 </span>
          <a-textarea
            v-else
            v-model="form.content"
            placeholder="请输入评价内容"
            disabled
            allow-clear
          />
        </a-form-item>
        <a-form-item>
          <div class="score-content">
            <span>物流评分：{{ detailInfo.deliveryScore }}</span>
            <span>服务评分：{{ detailInfo.serviceScore }}</span>
            <span>描述评分：{{ detailInfo.descriptionScore }}</span>
          </div>
        </a-form-item>
        <a-form-item
          v-if="detailInfo.haveImage == 1"
          field="image"
          label="评价图片"
        >
          <div v-if="image && image.length">
            <div v-for="(item, _index) in image" :key="_index">
              <a-image :width="100" :src="item"></a-image>
            </div>
          </div>
        </a-form-item>
        <a-form-item field="reply" :rules="[REQUIRED]" label="回复内容">
          <a-textarea
            v-if="isReply == true"
            v-model="form.reply"
            disabled
            allow-clear
          />
          <a-textarea
            v-else
            v-model="form.reply"
            placeholder="请输入回复内容"
            allow-clear
          />
        </a-form-item>
        <a-form-item
          v-if="detailInfo.haveReplyImage == 1 || isReply == false"
          label="回复图片"
          field="replyImage"
        >
          <div v-if="form.replyImage">
            <div v-for="(item, _index) in form.replyImage" :key="_index">
              <a-image :width="100" :src="item"></a-image>
            </div>

            <!--<upload-image :clear="true" @change="insertImage($event,'goodsGalleryList')" />-->
          </div>

          <div v-if="form.replyImage.length === 0">
            <a-button @click="handleClickOssManages()">上传图片</a-button>
          </div>
          <!-- <a-upload
            v-else
            ref="uploadRef"
            list-type="picture-card"
            :headers="{ token: accessToken }"
            :action="uploadFile"
            :on-success="handleSuccess"
            :on-error="handleError"
            :limit="5"
            @before-upload="beforeUpload"
          >
          </a-upload> -->
        </a-form-item>
      </a-form>
      <template #footer>
        <div style="text-align: right">
          <a-button @click="modalVisible = false">取消</a-button>
          <a-button
            v-if="isReply == false"
            style="margin-left: 10px"
            type="primary"
            @click="handleSubmit"
            >回复</a-button
          >
        </div>
      </template>
    </a-modal>
    <!--上传图片弹框-->
    <a-modal
      v-model:visible="showOssManages"
      :width="966"
      title="选择图片"
      :body-style="{ paddingTop: '0px', paddingBottom: '0px' }"
      @ok="ossManagesOk"
      @cancel="ossManagesCancel"
    >
      <ossManages
        :initialize="showOssManages"
        @selected="ossManagesSelected"
      ></ossManages>
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
  import searchTable from '@/components/search-column/index.vue';
  import tablePage from '@/components/table-pages/index.vue';
  import {
    getMemberReview,
    getMemberInfoReview,
    replyMemberReview,
  } from '@/api/member';
  import { SearchRule, MethodsRule, ColumnsDataRule } from '@/types/global';
  import { gradeList, commentStatus, replyStatus } from '@/utils/tools';
  import ossManages from '@/components/oss-manage/index.vue';
  import { Message } from '@arco-design/web-vue';
  import { ref } from 'vue';
  import store from '@/utils/storage';
  import uploadFile from '@/api/common';
  import { REQUIRED } from '@/utils/validator';
  const picVisible = ref(false); // 图片的modal
  const picFile = ref({ url: '' }); // 文件数据
  const showOssManages = ref(false); // 上传图片弹框
  const ossManagesList = ref([]);
  // 携带toekn
  const accessToken = ref(store.getAccessToken());
  const fileFormat = ref<Array<string>>(['jpg', 'jpeg', 'png', 'gif', 'bmp']);
  interface formRule {
    id: string | number;
    replyImage: any;
    reply: string;
    content: string;
  }
  const tablePageRef = ref<any>();
  const gradeStatusVar = ref<string>('GOOD');
  const apiParams = ref<any>({ grade: gradeStatusVar.value });
  const modalVisible = ref<boolean>(false); // 详情弹框
  const isReply = ref<boolean>(false); // 回复状态
  const image = ref<any>([]); // 评论图片
  const detailInfo = ref<any>({});
  const form = ref<formRule>({
    id: '',
    replyImage: [],
    reply: '',
    content: '',
  });
  const formRef = ref<any>();
  const columnsSearch: Array<SearchRule> = [
    {
      label: '会员昵称',
      model: 'memberName',
      disabled: false,
      input: true,
    },
    {
      label: '商品名称',
      model: 'goodsName',
      disabled: false,
      input: true,
    },
    {
      label: '评价时间',
      disabled: false,
      datePicker: {
        type: 'range',
      },
    },
  ];

  const columnsTable: ColumnsDataRule[] = [
    {
      title: '会员ID',
      dataIndex: 'memberId',
    },
    {
      title: '会员昵称',
      dataIndex: 'memberName',
    },
    {
      title: '商品名称',
      width: 300,
      dataIndex: 'goodsName',
    },
    {
      title: '评价内容',
      width: 200,
      dataIndex: 'content',
    },
    {
      title: '评论',
      dataIndex: 'grade',
      slot: true,
      slotData: {
        badge: gradeList,
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      slot: true,
      slotData: {
        badge: commentStatus,
      },
    },
    {
      title: '回复状态',
      dataIndex: 'replyStatus',
      slot: true,
      slotData: {
        badge: replyStatus,
      },
    },
    {
      title: '创建日期',
      width: 200,
      dataIndex: 'createTime',
    },
  ];

  const sortMethods: MethodsRule = {
    title: '操作',
    width: 100,
    methods: [
      {
        title: '详细',
        callback: 'detail',
        type: 'text',
        status: 'success',
      },
    ],
  };
  // 回复图片上传成功回调
  const handleSuccess = (res: any) => {
    if (res.response.success) {
      Message.success('上传成功');
      form.value.replyImage.push(res.response.result);
    }
  };
  // 回复图片上传失败
  const handleError = () => {
    Message.error('上传失败');
  };
  // 上传前校验
  const beforeUpload = (file: any) => {
    return new Promise((resolve, reject) => {
      if (
        !fileFormat.value.includes(
          file.name.split('.')[file.name.split('.').length - 1]
        )
      ) {
        reject(new Error('上传失败'));
        Message.error(`请选择 .jpg .jpeg .png .gif .bmp格式文件`);
      } else if (Number((file.size / 1024).toFixed(0)) > 1024) {
        reject(new Error('上传失败'));
        Message.error(`所选文件大小过大, 不得超过1M`);
      } else {
        resolve(true);
      }
    });
  };
  const details = async (v: any) => {
    const res = await getMemberInfoReview(v.record.id);
    if (res.data.code == 200) {
      form.value.id = res.data.result.id;
      form.value.reply = res.data.result.reply;
      form.value.content = res.data.result.content;
      form.value.replyImage = res.data.result.replyImage
        ? res.data.result.replyImage.split(',')
        : [];
      if (res.data.result.images) {
        image.value = (res.data.result.images || '').split(',');
      }
      detailInfo.value = res.data.result;
      isReply.value = res.data.result.replyStatus;
    }
    modalVisible.value = true;
  };
  const handleSubmit = async () => {
    const auth = await formRef.value?.validate();
    if (!auth) {
      const params = {
        id: form.value.id,
        reply: form.value.reply,
        replyImage: form.value.replyImage,
      };
      replyMemberReview(form.value.id, params).then((res) => {
        if (res.data.code == 200) {
          Message.success('回复成功');
          modalVisible.value = false;
          tablePageRef.value.init();
        }
      });
    }
  };

  // 查看
  const look = (v: any) => {
    picFile.value.url = v;
    picVisible.value = true;
  };
  // 移除图片
  const handleRemoveImage = (index: number | string) => {
    form.value.replyImage.splice(index, 1);
  };
  // 点击上传图片按钮
  const handleClickOssManages = () => {
    showOssManages.value = true;
  };
  // 上传图片弹框确认
  const ossManagesOk = () => {
    showOssManages.value = false;
    form.value.replyImage = ossManagesList.value.map((item: any) => item.url);
  };
  // 从子组件获取选择的图片
  const ossManagesSelected = (value: any) => {
    ossManagesList.value = value;
  };
  // 上传图片弹框取消
  const ossManagesCancel = () => {
    showOssManages.value = false;
  };
</script>

<style lang="less" scoped>
  .score-content {
    margin: 5px 0;
    span {
      margin-right: 20px;
    }
  }
</style>
